package com.xxwy.maxheap;

import com.xxwy.array.Array;


/**
 * @author xxwy
 */
public class MaxHeap<E extends Comparable<E>> {

    private Array<E> data;


    public MaxHeap(int capacity) {
        data = new Array<>(capacity);
    }

    public MaxHeap() {
        data = new Array<>();
    }

    public MaxHeap(E[] arr) {
        data = new Array<>(arr);
        for (int i = parent(arr.length - 1); i >= 0; i--) {
            siftDown(i);
        }
    }


    public int getSize() {
        return data.getSize();
    }

    public boolean isEmpty() {
        return data.isEmpty();
    }

    /**
     * 返回index的父节点的索引
     *
     * @param index
     * @return
     */
    private int parent(int index) {
        if (index == 0) {
            throw new IllegalArgumentException("index-0 doesn't have parent");

        }
        return (index - 1) / 2;
    }

    private int leftChild(int index) {
        return index * 2 + 1;
    }

    private int rightChild(int index) {
        return index * 2 + 2;
    }

    private void swap(int i, int j) {
        if (i < 0 || i >= getSize() || j < 0 || j >= getSize()) {
            throw new IllegalArgumentException("index is illegal");
        }
        E temp = data.get(i);
        data.set(i, data.get(j));
        data.set(j, temp);
    }

    public void add(E e) {
        data.addLast(e);
        siftUp(data.getSize() - 1);
    }

    /**
     * 上浮
     *
     * @param index
     */
    private void siftUp(int index) {
        while (index > 0 && data.get(parent(index)).compareTo(data.get(index)) < 0) {
            swap(index, parent(index));
            index = parent(index);
        }
    }

    public E findMax() {
        if (getSize() == 0) {
            throw new IllegalArgumentException("can not findMax when maxheap is empty");
        }
        return data.getFirst();
    }

    public E removeMax() {
        E first = findMax();
        swap(0, getSize() - 1);
        data.removeLast();
        siftDown(0);
        return first;
    }

    /**
     * 高能
     *
     * @param index
     */
    private void siftDown(int index) {
        while (leftChild(index) < getSize()) {
            int j = leftChild(index);
            if ((j + 1) < getSize() && data.get(j + 1).compareTo(data.get(j)) > 0) {
                j = rightChild(index);
            }
            if (data.get(index).compareTo(data.get(j)) >= 0) {
                break;
            }
            swap(index, j);
            index = j;
        }
    }

    public E replace(E e) {
        if (getSize() == 0) {
            throw new IllegalArgumentException("maxheap is empty");
        }
        E max = findMax();
        data.set(0, e);
        siftDown(0);
        return max;
    }


}
